package cn.com.connext.scrm.service;

import cn.com.connext.scrm.exception.ServiceErrorCode;
import cn.com.connext.scrm.service.dto.CouponDTO;
import cn.com.connext.scrm.utils.ExcelUtil;
import com.alibaba.fastjson.JSON;
import com.connext.common.exception.ServiceException;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class AnalysisExcel {
    private static final Logger log = LoggerFactory.getLogger(AnalysisExcel.class);

    public List<CouponDTO> importExcelFile(MultipartFile file) {
        List<CouponDTO> resultList = new ArrayList<>();
        //校验文件名称
        String originalFilename = file.getOriginalFilename();
        int indexOfLastPoint = originalFilename.lastIndexOf(".");
        if (indexOfLastPoint == -1) {
            log.info(ServiceErrorCode.ILLEGAL_FILE.getMessage() + "error 非法文件={},size={}，ContentType={}", originalFilename, file.getSize(), file.getContentType());
            throw new ServiceException(ServiceErrorCode.ILLEGAL_FILE);
        }
        Workbook workbook = ExcelUtil.getWorkBook(file);
        //获取文件 File
        File excelFile = null;
        try {
            // 获取文件名
            // 获取文件前缀与后缀
            String prefix = originalFilename.substring(0, indexOfLastPoint);
            String suffix = originalFilename.substring(indexOfLastPoint);
            // 用uuid作为文件名，防止生成的临时文件重复
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            excelFile = File.createTempFile(prefix + uuid, suffix);
            Sheet sheet = workbook.getSheetAt(0);//读取sheet(从0计数)
            int rowNum = sheet.getLastRowNum();//读取行数(从0计数)
            for (int i = 1; i < rowNum; i++) {
                Row row = sheet.getRow(i);//获得行
                row.getCell(0).setCellType(CellType.STRING);
                row.getCell(1).setCellType(CellType.STRING);
                row.getCell(3).setCellType(CellType.STRING);
                String id = row.getCell(0).toString();
                String couponName = row.getCell(1).toString();
                Date periodValidity = row.getCell(2).getDateCellValue();
                System.out.println(periodValidity);
                log.info("----------={}",periodValidity);
                String url = row.getCell(3).toString();
                CouponDTO couponDTO = new CouponDTO();
                couponDTO.setCouponId(id);
                couponDTO.setCouponName(couponName);
                if (null !=periodValidity) {
                    couponDTO.setPeriodValidity(periodValidity);
                }
                couponDTO.setUrl(url);
                couponDTO.setState(0);
                resultList.add(couponDTO);
            }
        } catch (Exception e) {
            log.error("error={}", e);
        } finally {
            //程序结束时，删除临时文件
            deleteFile(excelFile);
        }
        if (resultList == null || resultList.size() == 0) {
            throw new ServiceException(ServiceErrorCode.EMPTY_EXCEL_DATA);
        }
        log.info("resultList:{}", resultList.size());
        return resultList;
    }

    /**
     * 删除
     *
     * @param files
     */
    private void deleteFile(File... files) {
        for (File file : files) {
            if (file.exists()) {
                try {
                    boolean delete = file.delete();
                } catch (Exception e) {
                    log.error("ERROR 文件删除时候出错={}，filePath={}", e, file.getPath());
                }
            }
        }
    }
}
